package network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpEchoServer {
    private DatagramSocket socket = null;

    public UdpEchoServer(int port) throws SocketException {
        // 手动指定服务器的端口号
        socket = new DatagramSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动 !");
        while(true) {
            // 1. 接收客户端发送的请求并解析
            DatagramPacket requestPacket = new DatagramPacket(new byte[2048], 2048);
            socket.receive(requestPacket);
            // 对请求进行解析
            String request = new String(requestPacket.getData(), 0, requestPacket.getLength());
            // 2. 根据请求计算响应
            // 此处为回响服务器，请求与响应一致
            String response = process(request);
            // 3. 将响应发送给客户端
            DatagramPacket responsePack = new DatagramPacket(response.getBytes(),0, response.getBytes().length,
                    requestPacket.getSocketAddress());
            socket.send(responsePack);
            // 4. 打印日志，显示发送请求的客户端的ip地址、端口、请求内容和服务器回复内容
            System.out.printf("[ip = %s, port = %d], request:%s ,response:%s\n", requestPacket.getAddress().toString(), requestPacket.getPort(),
                    request, response);
        }
    }

    protected String process(String request) {
        return request;
    }


    public static void main(String[] args) throws IOException {
        UdpEchoServer server = new UdpEchoServer(8080);
        server.start();
    }
}
